package com.sikaryofficial.workbench.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * @author : qinjinyuan
 * @desc : 本地缓存Caffeine
 * @date : 2024/09/28 8:53
 */

@Component
public class WorkBenchLocalCache {
    private final Cache<String, byte[]> cache;

    public WorkBenchLocalCache() {
        // 初始化Caffeine缓存，存储键为String类型，值为byte[]类型（序列化后的对象）
        this.cache = Caffeine.newBuilder()
                //最后一次写入后经过固定时间过期
                .expireAfterWrite(5, TimeUnit.SECONDS)
                //maximumSize=[long]: 缓存的最大条数
                .maximumSize(1000)
                .build();
    }

    public void put(String key, Serializable value) {
        try {
            // 将对象序列化为字节数组
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(value);
            byte[] serializedValue = byteArrayOutputStream.toByteArray();

            // 将序列化后的字节数组存储到缓存中
            cache.put(key, serializedValue);
        } catch (IOException e) {
            // 处理序列化时的异常
            throw new RuntimeException("Failed to serialize value", e);
        }
    }

    public <T extends Serializable> T get(String key, Class<T> type) {
        byte[] serializedValue = cache.getIfPresent(key);
        if (serializedValue != null) {
            try {
                // 将字节数组反序列化为对象
                ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(serializedValue));
                return (T) objectInputStream.readObject();
            } catch (IOException | ClassNotFoundException e) {
                // 处理反序列化时的异常
                throw new RuntimeException("Failed to deserialize value", e);
            }
        }
        return null;
    }

    public <T extends Serializable> T get(String key) {
        byte[] serializedValue = cache.getIfPresent(key);
        if (serializedValue != null) {
            try {
                // 将字节数组反序列化为对象
                ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(serializedValue));
                return (T) objectInputStream.readObject();
            } catch (IOException | ClassNotFoundException e) {
                // 处理反序列化时的异常
                throw new RuntimeException("Failed to deserialize value", e);
            }
        }
        return null;
    }


    public void delete(String key) {
        byte[] serializedValue = cache.getIfPresent(key);
        if (serializedValue != null) {
            try {
                cache.invalidate(key);
            } catch (Exception e) {
                throw new RuntimeException("Failed", e);
            }
        }
    }

}
